import axios from 'axios'
import qs from 'qs'
import md5 from 'js-md5'; //md5加密
import router from "../router";
import {
    Notify
} from "vant";

// 创建axios实例
const service = axios.create({
    baseURL: 'http://chenjl.51vip.biz/', // 本地测试地址
    // baseURL: 'https://api.haipinwangluo.top/', // 线上地址地址
    withCredentials: true, // 跨域请求时发送cookies
    timeout: 5000 // 请求超时
})

/**
 * 反向字符串拼接
 * @param json
 * @returns {string}
 */
export function valueReverse(json) {
    let arrays = "myistest0000";
    for (var key in json) {
        if (key == "signature") {
            continue;
        }
        arrays += "," + key;
    }
    if (arrays == "myistest0000") {
        return;
    }

    let array = arrays.split(",");
    array.sort().reverse();
    var jsonStr = "";
    for (var i in array) {
        if ((array[i] == "myistest0000" || json[array[i]] == "" || json[array[i]] == undefined) && json[array[i]] !=
            0) {
            continue;
        }
        // jsonStr += json[array[i]];
        if (typeof (json[array[i]]) == "object") {
            jsonStr += JSON.stringify(json[array[i]]);
        } else {
            jsonStr += json[array[i]];
        }
    }
    return jsonStr;
}
// 请求拦截器
service.interceptors.request.use(
    config => {
        // 在发送请求之前做些什么		
        if (config.method === 'post') {
            const data = qs.parse(config.data)
            data.token = localStorage.getItem('token')
            config.data = qs.stringify({
                signature: md5(md5(valueReverse(data))),
                ...data
            })
            // || config.method === 'delete'
        } else if (config.method === 'put') {
            config.headers = {
                'Content-Type': 'application/x-www-form-urlencoded'
            }
            const data = qs.parse(config.data)

            data.token = localStorage.getItem('token')
            config.data = qs.stringify({
                signature: md5(md5(valueReverse(data))),
                ...data

            })

        } else {
            config.headers = {
                'Content-Type': 'application/x-www-form-urlencoded'
            }

            config.data = qs.stringify(config.data)
            // 添加默认值
            config.params = {
                token: localStorage.getItem('token'),
                ...config.params
            }

            config.params.signature = md5(md5(valueReverse(config.params)));
        }
        return config
    },
    error => {
        // 处理请求错误
        console.log(error) // for debug
        return Promise.reject(error)
    }
)

// 响应拦截器
service.interceptors.response.use(
    /**
     * 如果您想获取http信息，如标头或状态
     * Please return  response => response
     */

    /**
     *通过自定义代码确定请求状态
     * Here is just an example
     * 您还可以通过HTTP状态码来判断状态
     */
    response => {
        const res = response.data
        // if the custom code is not 20000, it is judged as an error.
        if (res.status !== 0) {
            Notify({
                message: res.msg || 'Error',
                type: 'danger',
                duration: 5 * 1000
            })
            if (res.status === 106 || res.status === 401) {
                router.replace({
                    path: '/login'
                })
                localStorage.removeItem("token");
                localStorage.removeItem("userInfo");
            }
            return Promise.reject(new Error(res.msg || 'Error'))
        } else {
            return res
        }
    },
    error => {
        console.log('err' + error) // for debug
        Notify({
            message: 'netWork error',
            type: 'danger',
            duration: 2 * 1000
        })
        return Promise.reject(error)
    }
)

export default service
